<template>
  <div class="admin">
    <el-card class="box-card" v-if="status === 'index'">
      <el-row>
        <el-select
          v-model="searchParams.role_id"
          placeholder="请选择角色"
          clearable
          size="mini"
        >
          <el-option
            v-for="item in roleArr"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
        <el-input
          v-model="searchParams.username"
          clearable
          placeholder="请输入管理员名称"
          style="width:200px"
          size="mini"
        ></el-input>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getData"
          v-if="has('admins/index')"
          >搜索</el-button
        >
        <el-button
          type="info"
          icon="el-icon-refresh"
          size="mini"
          @click="reset"
          v-if="has('admins/index')"
          >重置</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="add"
          v-if="has('admins/store')"
          >添加</el-button
        >
      </el-row>
      <el-table
        :data="data.data"
        v-loading="table_loading"
        row-key="id"
        style="width: 100%;margin:10px auto"
        size="mini"
        :header-cell-style="{ background: '#f3f8fe', color: '#333' }"
      >
        <el-table-column
          fixed
          prop="id"
          label="ID"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="管理员名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="role.name"
          label="所属角色"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="created_at"
          label="创建时间"
          align="center"
        ></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="edit(scope.row.id)"
              v-if="has('admins/show')"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="del(scope.row.id, scope.$index)"
              v-if="has('admins/del')"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        style="text-align:center;margin:20px 0;"
        :current-page="searchParams.page"
        :page-sizes="pageSizes"
        layout="total,prev, pager, next,sizes"
        :total="data.total"
        @size-change="changeSize"
        @current-change="changePage"
      ></el-pagination>
    </el-card>

    <el-dialog title="添加管理员" :visible.sync="addStatus" @close="init">
      <el-form
        :model="editParams"
        :rules="rules"
        ref="form"
        label-width="120px"
      >
        <el-form-item label="角色" prop="role_id">
          <el-select v-model="editParams.role_id" placeholder="请选择角色">
            <el-option
              v-for="item in roleArr"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理员名称" prop="username">
          <el-input v-model="editParams.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码" prop="password">
          <el-input
            v-model="editParams.password"
            type="password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="re_password">
          <el-input
            v-model="editParams.re_password"
            type="password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="init">取 消</el-button>
        <el-button
          type="primary"
          @click="submit('form', 1)"
          v-if="has('admins/store')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="编辑管理员" :visible.sync="editStatus" @close="init">
      <el-form
        :model="editParams"
        :rules="rules"
        ref="form"
        label-width="120px"
      >
        <el-form-item label="角色" prop="role_id">
          <el-select v-model="editParams.role_id" placeholder="请选择角色">
            <el-option
              v-for="item in roleArr"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理员名称" prop="username">
          <el-input v-model="editParams.username" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="init">取 消</el-button>
        <el-button
          type="primary"
          @click="submit('form', 2)"
          v-if="has('admins/edit')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from "../../api/api.js";
export default {
  name: "menu",
  data() {
    return {
      status: "index", // 页面控制
      data: [], // 表格诗句
      table_loading: true, // 表格加载中
      loading: false, //全局加载中
      roleArr: [],
      addStatus: false,
      editStatus: false,
      pageSizes: [10, 20, 50, 100, 200, 500, 800, 1000, 2000], // 每页条数默认10
      searchParams: {
        // 搜索参数
        page: 1,
        limit: 10,
        role_id: ""
      },
      editParams: {
        // 添加/编辑参数
        role_id: "",
        username: "",
        password: "",
        re_password: "",
        role: {
          id: "",
          name: ""
        }
      },
      rules: {
        // 验证规则
        role_id: [{ required: true, message: "请选择角色", trigger: "change" }],
        username: [
          { required: true, message: "请输入管理员名称", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入管理员密码", trigger: "blur" }
        ],
        re_password: [
          { required: true, message: "请再次输入密码", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getData();
    this.getRole();
  },

  methods: {
    // 加载中
    load() {
      this.loading = this.$loading({
        lock: true,
        text: "数据加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },
    getRole() {
      api.admins
        .role()
        .then(res => {
          if (res.data.code == 200) {
            this.roleArr = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 取消加载
    unload() {
      this.loading.close();
    },
    // 获取所有分类
    getData() {
      this.table_loading = true;
      api.admins
        .index({ params: this.searchParams })
        .then(res => {
          if (res.data.code == 200) {
            this.table_loading = false;
            this.data = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 重置搜索参数重新搜索
    reset() {
      this.init();
      this.getData();
    },
    // 初始化
    init() {
      this.searchParams.role_id = "";
      this.editParams = {
        role_id: "",
        username: "",
        password: "",
        re_password: "",
        role: {
          id: "",
          name: ""
        }
      };
      this.addStatus = false;
      this.editStatus = false;
    },
    // 改变每页条数时
    changeSize(limit) {
      this.searchParams.limit = limit;
      this.getData();
    },
    // 改变当前页码时
    changePage(page) {
      this.searchParams.page = page;
      this.getData();
    },
    // 添加页面
    add() {
      this.addStatus = true;
    },
    // 编辑页面
    edit(id) {
      this.load();
      api.admins
        .show(id)
        .then(res => {
          this.unload();
          if (res.data.code == 200) {
            this.editStatus = true;
            this.editParams = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 保存添加或编辑
    submit(formName, type) {
      this.$refs[formName].validate((valid, error) => {
        if (valid) {
          this.load();
          // 添加
          if (type === 1) {
            api.admins
              .store(this.editParams)
              .then(res => {
                this.unload();
                if (res.data.code == 200) {
                  this.reset();
                }
              })
              .catch(error => {
                console.log(error);
              });
          } else if (type == 2) {
            // 编辑
            api.admins
              .edit(this.editParams.id, this.editParams)
              .then(res => {
                this.unload();
                if (res.data.code == 200) {
                  this.reset();
                }
              })
              .catch(error => {
                console.log(error);
              });
          }
        } else {
          this.$message.error(Object.values(error)[0][0].message);
          return false;
        }
      });
    },
    // 删除
    del(id, index) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      })
        .then(() => {
          api.admins
            .del(id)
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.data.data.splice(index, 1);
                this.data.total--;
              }
            })
            .catch(error => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>

<style scoped lang="less">
.admin {
  margin: 0 auto;
  .search {
    margin: 0 auto 10px auto;
  }
}
</style>
